package com.tianhao.luo.helper;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 模拟6辆车，停3个车位
 *
 * @author tianhao.luo@hand-china.com
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                // 抢占车位
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+" 获取到了车位");
                    // 设置随机停车市场
                    TimeUnit.SECONDS.sleep(new Random(10).nextInt(3));
                    System.out.println(Thread.currentThread().getName()+" 离开了车位----");
                    semaphore.release();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i+1)).start();
        }
    }
}
